//
//  HTCoreDataManager.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/21.
//

import Foundation
import CoreData

class HTCoreDataManager {

  init() {}

  private lazy var var_persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "MagaCore")

    container.loadPersistentStores(completionHandler: { _, error in
      _ = error.map { fatalError("Unresolved error \($0)") }
    })
    return container
  }()

  private var var_mainContext: NSManagedObjectContext {
    return var_persistentContainer.viewContext
  }

  // -MARK: Functions

  func ht_fetchSearchHistoryData() -> [SearchHistory] {
    let var_fetchRequest: NSFetchRequest<SearchHistory> = SearchHistory.fetchRequest()
    guard let requests = try? var_mainContext.fetch(var_fetchRequest) else { return [] }
    return requests.reversed()
  }

  func ht_addNewSearchHistory(name: String) {
    let var_result = ht_fetchSearchHistoryData();
    for result in var_result {
      if (result.string_name == name) {
        var_mainContext.delete(result)
      }
    }

    let var_newSearchHistory = SearchHistory(context: var_mainContext)
    var_newSearchHistory.string_name = name

    do {
      try self.var_mainContext.save()
    } catch {
      let error = error as NSError
      print("Unable to Save: \(error)")
    }
  }

  func ht_deleteAllSearchHistory() {
    let var_result = ht_fetchSearchHistoryData();
    for result in var_result {
      var_mainContext.delete(result)
    }

    do {
      try self.var_mainContext.save()
    } catch {
      let error = error as NSError
      print("Unable to Delete: \(error)")
    }
  }

  func ht_fetchRecentPlayData() -> [RecentPlay] {
    let var_fetchRequest: NSFetchRequest<RecentPlay> = RecentPlay.fetchRequest()
    guard let requests = try? var_mainContext.fetch(var_fetchRequest) else { return [] }
    return requests.reversed()
  }

  func ht_addNewRecentPlay(anime: HTAnime) {
    let var_recentPlays = ht_fetchRecentPlayData()

    for result in var_recentPlays {
      if (result.id == anime.var_id) {
        var_mainContext.delete(result)
      }
    }

    let var_newRecentPlay = RecentPlay(context: var_mainContext)
    var_newRecentPlay.id = anime.var_id
    var_newRecentPlay.cover = anime.var_cover
    var_newRecentPlay.title = anime.var_title
    var_newRecentPlay.ep = anime.var_ep
    var_newRecentPlay.cur_ep = anime.var_cur_ep
    var_newRecentPlay.cur_epId = anime.var_cur_epId
    var_newRecentPlay.progressRate = anime.var_progressRate!
    var_newRecentPlay.startTime = anime.var_startTime
    var_newRecentPlay.during = anime.var_during!

    do {
      try self.var_mainContext.save()
    } catch {
      let error = error as NSError
      print("Unable to Save: \(error)")
    }
  }

  func ht_deleteRecentPlay(ids: [String]) {
    let var_recentPlays = ht_fetchRecentPlayData()
    for result in var_recentPlays {
      if (ids.contains(result.id!)) {
        var_mainContext.delete(result)
      }
    }

    do {
      try self.var_mainContext.save()
    } catch {
      let error = error as NSError
      print("Unable to Delete: \(error)")
    }
  }

  func ht_fetchAdConfigData() -> [AdConfig] {
    let var_fetchRequest: NSFetchRequest<AdConfig> = AdConfig.fetchRequest()
    guard let requests = try? var_mainContext.fetch(var_fetchRequest) else { return [] }
    return requests.reversed()
  }

  func ht_addAdConfig(adConfig: HTAdConfig) {
    let var_adConfigs = ht_fetchAdConfigData()

    for result in var_adConfigs {
      var_mainContext.delete(result)
    }

    let var_newAdConfig = AdConfig(context: var_mainContext)
    var_newAdConfig.config = adConfig.toJSONString()!

    do {
        try self.var_mainContext.save()
    } catch {
        let error = error as NSError
        print("Unable to Save: \(error)")
    }
  }
}
